package cn.intotw.rdcj.admin.shiro;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.subject.WebSubject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class AutoLoginBaseFilter extends org.apache.shiro.web.filter.authc.AuthenticatingFilter{


    @Override
    protected AuthenticationToken createToken(ServletRequest request,
                                              ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest)request;

        return new UsernamePasswordToken("123", "456");
    }

    @Override
    protected boolean onAccessDenied(ServletRequest arg0, ServletResponse arg1)
            throws Exception {
        return false;
    }

    /**
     * 尝试自动登录
     * 关注微信且用户状态是未注册的才可以登录成功
     * 
     * @param request
     * @param response
     * @return true 登录成功 否则失败
     */
    @SuppressWarnings("deprecation")
    public boolean tryLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest)request;

        PrincipalCollection principals = new SimplePrincipalCollection(req.getHeader("userId"), "rdcjAdminRealm");
        WebSubject.Builder builder = new WebSubject.Builder(request, response);
        builder.principals(principals);
        builder.authenticated(true);
        WebSubject subject = builder.buildWebSubject();
        ThreadContext.bind(subject);
        return true;
    }

}
